package com.jet.chat.command;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.jet.chat.message.Message;
import com.jet.chat.server.ChatServer;
import com.jet.chat.server.ChatSession;

public abstract class ChatCommandAbstract implements ChatCommand {
	protected final Pattern pattern;

	public ChatCommandAbstract(String string) {
		pattern = Pattern.compile(string);
	}
	
	@Override
	public void execute(ChatServer chatServer, ChatSession chatSession, Message chatMessage) throws Exception {
		Matcher matcher = pattern.matcher(chatMessage.getContent());
		
		//[ek] TODO dublication fragment detected in all commands. Please reuse the code.
		if (!matcher.matches()) {
			chatSession.getWriter().write(new Message("invalid command format"));
		} else {
			executeCommand(matcher, chatServer, chatSession, chatMessage);
		}
	}

	protected abstract void executeCommand(Matcher matcher, ChatServer chatServer, ChatSession chatSession, Message chatMessage) throws Exception;

}
